from email import encoders
from email.header import Header
from email.utils import parseaddr
from email.utils import formataddr
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.multipart import MIMEBase
import smtplib


def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, "utf-8").encode(), addr))


from_addr = "q1750900216@aliyun.com"  # 输入Email地址和口令
password = "123654788m"
to_addr = "q1750900216@aliyun.com"  # 输入收件人地址
s_server = "smtp.aliyun.com"  # 输入SMTP服务器地址
# -------------------------------------纯文本---------------------------------------------------------------------------
# msg = MIMEText("Hello,This message send from Python!", "plain", "utf-8")  # 纯文本邮件
# 构造MIMEText对象时，第一个参数就是邮件正文，第二个参数是MIME的subtype，
# 传入'plain'表示纯文本，最终的MIME就是'text/plain'，最后一定要用utf-8编码保证多语言兼容性。
# -------------------------------------HTML格式-------------------------------------------------------------------------
# msg = MIMEText('<html><body><h1>Hello</h1><p>send by <a href="http://www.python.org">Python</a>...</p></body></html>', 'html', 'utf-8')
# -------------------------------------带附件的-------------------------------------------------------------------------
msg = MIMEMultipart("alternative")
msg["From"] = _format_addr("Email is send by:<%s>" % from_addr)
msg["To"] = _format_addr("发件人：<%s>" % to_addr)
msg["Subject"] = Header("Test Python Send Email attach adjunct！", "utf-8").encode()
msg.attach(MIMEText("Test attach adjunct!", "plain", "utf-8"))  # 邮件正文
msg.attach(MIMEText("<html><body><h1>Hello</h1><p><img src='cid:0'></p></body></html>", "html", "utf-8"))
# 添加附件
with open("SMTP.jpg", "rb") as pic:
    mime = MIMEBase("image", "jpg", filename="SMTP.jpg")
    mime.add_header("Content-Disposition", "attachment", filename="SMTP.jpg")
    mime.add_header("Content-ID", "<0>")
    mime.add_header("X-Attachment-Id", "0")
    mime.set_payload(pic.read())
    encoders.encode_base64(mime)
    msg.attach(mime)
server = smtplib.SMTP(s_server, 25)  # SMTP协议默认端口是25
# ----------------------------------------加密--------------------------------------------------------------------------
# smtp_port = 587
# server = smtplib.SMTP(s_server, smtp_port)
# server.starttls()
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()
